<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel="stylesheet" href="openlayer/ol465/ol.css" type="text/css" />
    <script src="openlayer/ol465/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="openlayer/ol465/ol.js"></script>
    <script src="js/data.js"></script>
    <script src="js/pip.js"></script>
    <script src="js/kriging.js"></script>
    <script src="js/turf.min.js"></script>
    <script src="js/bj.js"></script>
  </head>
  <style></style>

  <body>
    <div id="map" class="map"></div>
    <script>
      window.onload = () => {
        var jd = 500;
        var breaks = [0.1, 10, 25, 50, 100, 250, 400, 600, 800, 1000, 2000000];
        function getColor(z) {
          for (var i = 0; i < breaks.length; i++) {
            if (breaks[i] > z.split("-")[1]) {
              console.log(z);
              console.log(i);
              return params.colors[i - 1];
            }
          }
        }
        let params = {
          mapCenter: [116.4, 39.9],
          maxValue: 100,
          krigingModel: "spherical", //model还可选'gaussian','spherical',exponential
          krigingSigma2: 0,
          krigingAlpha: 100,
          canvasAlpha: 0.75, //canvas图层透明度
          colors: [
            "#FFFFFF",
            "#A1F18D",
            "#3DBA3D",
            "#60B8FF",
            "#0000FF",
            "#FF00FF",
            "#800040",
            "#FFAA00",
            "#FF6600",
            "#E60000",
            "#502D0A",
          ],
          //             colors: ["255 255 255", "161 241 141", "61 186 61", "96 184 255", "0 0 255", "250 0 250","128 0 64",  "255 170 0","255 102 0","230 0 0","80 45 10 "],
        };
        let baseLayer = new ol.layer.Tile({
          title: "base",
          source: new ol.source.OSM(),
        });
        let map = new ol.Map({
          target: "map",
          layers: [baseLayer],
          view: new ol.View({
            center: params.mapCenter,
            projection: "EPSG:4326",
            zoom: 8,
          }),
        });
        let WFSVectorSource = new ol.source.Vector();
        let WFSVectorLayer = new ol.layer.Vector({
          source: WFSVectorSource,
        });
        map.addLayer(WFSVectorLayer);

        //添加选择和框选控件，按住Ctr键，使用鼠标框选采样点
        let select = new ol.interaction.Select();
        map.addInteraction(select);
        let dragBox = new ol.interaction.DragBox({
          condition: ol.events.condition.platformModifierKeyOnly,
        });
        console.log(dragBox);
        map.addInteraction(dragBox);

        for (let i = 0; i < data.features.length; i++) {
          if (data.features[i].attributes.z == 0) {
            continue;
          }

          let feature = new ol.Feature({
            geometry: new ol.geom.Point([
              data.features[i].attributes.x,
              data.features[i].attributes.y,
            ]),
            value: data.features[i].attributes.z,
          });
          feature.setStyle(
            new ol.style.Style({
              image: new ol.style.Circle({
                radius: 1,
                fill: new ol.style.Fill({ color: "#00F" }),
              }),
              //                 text: new ol.style.Text({
              //                     text: data.features[i].attributes.name+"_"+data.features[i].attributes.z+"",
              //                     font:"bold 12px Times New Roman",
              //                     fill: new ol.style.Fill({
              //                         color: '#fff'
              //                     })
              //                 })
            })
          );
          WFSVectorSource.addFeature(feature);
        }

        //设置框选事件
        let selectedFeatures = new Array();
        dragBox.on("boxend", () => {
          let extent = dragBox.getGeometry().getExtent();
          WFSVectorSource.forEachFeatureIntersectingExtent(
            extent,
            (feature) => {
              selectedFeatures.push(feature);
            }
          );
          console.log(extent);
          //             drawKriging(extent);
        });
        dragBox.on("boxstart", () => {
          //             selectedFeatures.clear();
        });

        //利用网格计算点集
        const gridFeatureCollection = function (grid, xlim, ylim) {
          var range = grid.zlim[1] - grid.zlim[0];
          var i, j, x, y, z;
          var n = grid.length; //列数
          var m = grid[0].length; //行数
          var pointArray = [];
          for (i = 0; i < n; i++)
            for (j = 0; j < m; j++) {
              x = i * grid.width + grid.xlim[0];
              y = j * grid.width + grid.ylim[0];
              //                     z = (grid[i][j] - grid.zlim[0]) / range;
              //                     if (z < 0.0) z = 0.0;
              //                     if (z > 1.0) z = 1.0;

              z = grid[i][j];
              pointArray.push(turf.point([x, y], { value: z }));
            }
          return pointArray;
        };
        //绘制kriging插值图
        let vectorLayer = null;
        const drawKriging = (extent) => {
          let values = [],
            lngs = [],
            lats = [];
          WFSVectorSource.forEachFeature(function (feature) {
            values.push(feature.getProperties().value);
            lngs.push(feature.getGeometry().getCoordinates()[0]);
            lats.push(feature.getGeometry().getCoordinates()[1]);
          });
          if (values.length > 3) {
            let variogram = kriging.train(
              values,
              lngs,
              lats,
              params.krigingModel,
              params.krigingSigma2,
              params.krigingAlpha
            );
            let polygons = [];
            //                 console.
            //                 polygons.push([
            //                     [extent[0], extent[1]], [extent[0], extent[3]],
            //                     [extent[2], extent[3]], [extent[2], extent[1]]
            //                 ]);
            let clipgeom = new ol.geom.Polygon(beijing);
            let ex = clipgeom.getExtent();
            console.log(ex);
            (() => {
                console.time('origin grid')
                kriging.grid(beijing, variogram, (ex[2] - ex[0]) / jd);
                console.timeEnd('origin grid')
            })()
            const grid = (() => {
                console.time('fast grid')
                const grid = kriging.fastGrid(
                    beijing,
                    variogram,
                    (ex[2] - ex[0]) / jd
                    );
                console.timeEnd('fast grid')
                return grid
            })()            
            let dragboxExtent = extent;

            if (vectorLayer !== null) {
              map.removeLayer(vectorLayer);
            }
            var vectorSource = new ol.source.Vector();
            vectorLayer = new ol.layer.Vector({
              source: vectorSource,
              opacity: 0.7,
              style: function (feature) {
                var color = getColor(feature.get("value"));
                var style = new ol.style.Style({
                  fill: new ol.style.Fill({
                    color: color,
                  }),
                  stroke: new ol.style.Stroke({
                    //边界样式
                    color: color,
                    width: 2,
                  }),
                });
                return style;
              },
            });
            //使用turf渲染等值面/线
            let fc = gridFeatureCollection(
              grid,
              [ex[0], ex[2]],
              [ex[1], ex[3]]
            );
            console.log("fc");
            console.log(fc);
            var collection = turf.featureCollection(fc);
            console.log(collection);

            var isobands = turf.isobands(collection, breaks, {
              zProperty: "value",
            });
            //                 var isobands = turf.isolines(collection, breaks, { zProperty: 'value' });

            //   				 var breaks = [1, 10, 20, 30, 50, 70, 100];
            //                 var isobands_options = {
            //                 			zProperty: "value",
            //                 		  commonProperties: {"fill-opacity": 0.8 },
            //                 		  	breaksProperties: [
            //                 		  	{fill: "#e3e3ff"},
            //                 		    {fill: "#c6c6ff"},
            //                 		    {fill: "#a9aaff"},
            //                 		    {fill: "#8e8eff"},
            //                 		    {fill: "#7171ff"},
            //                 		    {fill: "#5554ff"},
            //                 		    {fill: "#3939ff"},
            //                 		    {fill: "#1b1cff"}
            //                 		  ]
            //                 		};
            //                 var isobands = turf.isobands(collection, breaks, isobands_options);

            //                 isolines

            function sortArea(a, b) {
              return turf.area(b) - turf.area(a);
            }
            //按照面积对图层进行排序，规避turf的一个bug
            isobands.features.sort(sortArea);
            console.log(isobands);
            var polyFeatures = new ol.format.GeoJSON().readFeatures(isobands, {
              featureProjection: "EPSG:4326",
            });
            vectorSource.addFeatures(polyFeatures);

            map.addLayer(vectorLayer);
          } else {
            alert("有效样点个数不足，无法插值");
          }
        };

        drawKriging();
        //         let extent = [params.mapCenter[0] - .005, params.mapCenter[1] - .005, params.mapCenter[0] + .005, params.mapCenter[1] + .005];
        //         WFSVectorSource.forEachFeatureIntersectingExtent(extent, (feature) => {
        //             selectedFeatures.push(feature);
        //         });
        //         drawKriging(extent);
        console.log(1);
      };
    </script>
  </body>
</html>
